<template>
    <view class="manage_info_components contract_region">
        <div class="pub_input">
            <div class="li">
                <div class="title"><text class="xing">*</text> 客户名称</div>
                <div class="input">
                    <input class="inp" type="text" v-model="form.username" placeholder="请输入" placeholder-style="color:#bbb">
                </div>
            </div>
            <div class="li">
                <div class="title"><text class="xing">*</text> 性别</div>
                <div class="input input_right">
                    <picker :value="form.sex_index" :range="options.sex" @change="(data) => pickerChange('sex', data)">
                        <input class="inp" type="text" :value="form.sex" placeholder="请选择" placeholder-style="color:#bbb"
                            disabled>
                        <image class="right_icon" mode="aspectFit"
                            src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                    </picker>
                </div>
            </div>
            <div class="li">
                <div class="title"><text class="xing">*</text> 手机号</div>
                <div class="input">
                    <input class="inp" type="number" maxlength="11" v-model="form.phone" placeholder="请输入"
                        placeholder-style="color:#bbb">
                </div>
            </div>
            <div class="li">
                <div class="title"><text class="xing">*</text> 备用联系人手机</div>
                <div class="input">
                    <input class="inp" type="number" maxlength="11" v-model="form.backup_phone" placeholder="请输入"
                        placeholder-style="color:#bbb">
                </div>
            </div>
        </div>
        <div class="bind_room_div">
            <div class="title"><text class="xing">*</text> 绑定房间
                <!-- <image class="right_icon" mode="aspectFit" src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" /> -->
            </div>
            <div class="pub_input" style="width: 100%;">
                <div class="li">
                    <div class="title">选择区域</div>
                    <div class="input input_right">
                        <picker :value="room_keys[0].key" :range="options.region" range-key="areaName"
                            @change="(data) => pickerChange('region', data)">
                            <input class="inp" type="text" :value="room_keys[0].name" placeholder="请选择"
                                placeholder-style="color:#bbb" disabled>
                            <image class="right_icon" mode="aspectFit"
                                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                        </picker>
                    </div>
                </div>
                <div class="li" v-if="room_keys[0].id">
                    <div class="title">选择房间</div>
                    <div class="input input_right">
                        <picker :value="room_keys[1].key" :range="options.room" range-key="roomName"
                            @change="(data) => pickerChange('room', data)">
                            <input class="inp" type="text" :value="room_keys[1].name" placeholder="请选择"
                                placeholder-style="color:#bbb" disabled>
                            <image class="right_icon" mode="aspectFit"
                                src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_24.png" />
                        </picker>
                    </div>
                </div>
            </div>


            <div class="lis">
                <div class="pub_nodata_2" v-if="room_lists.length == 0">暂无房间</div>

                <uni-swipe-action ref="swipeAction">
                    <uni-swipe-action-item v-for="(item, index) in room_lists" :key="item.id">
                        <div class="li">{{ item.areaName }}{{ item.name }}</div>
                        <template v-slot:right>
                            <view class="del" @click="deleteRooms(index)">
                                <image class="icon" mode="aspectFit"
                                    src="https://sppcp-1322907932.cos.ap-beijing.myqcloud.com/app/img_53.png" />
                            </view>
                        </template>
                    </uni-swipe-action-item>
                </uni-swipe-action>


            </div>
        </div>
        <div class="pub_btns" v-if="editId == ''" :style="{ 'bottom': bottom }">
            <div class="pub_btn pub_btn_big_normal" @click="toSubmit">新增客户</div>
        </div>
        <div class="pub_btns pub_btns_big" v-if="editId != '' && userStatus != ''" :style="{ 'bottom': bottom }">
            <div class="pub_btn pub_btn_red" v-if="userStatus == 1" @click="changeStatus">禁用</div>
            <div class="pub_btn pub_btn_red" v-if="userStatus == 2" @click="changeStatus">启用</div>
            <div class="pub_btn_normal pub_btn_normal_border pub_btn_small" @click="toDelete">删除</div>
            <div class="pub_btn pub_btn_small" @click="toSubmit">保存并提交</div>
        </div>
    </view>
</template>

<script>
export default {
    props: {
        editId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            bottom: `calc(${getApp().globalData.statusBottomHeight}px + 32rpx)`,
            options: {
                sex: ['男', '女'],
                region: [],
                room: [],
            },
            form: {
                username: '',
                sex: '',
                sex_index: 0,
                phone: '',
                backup_phone: '',
                room_ids: []
            },
            room_keys: [{ name: '', key: '', id: '' }, { name: '', key: '', id: '' }],
            room_lists: [],
            userStatus: ''
        };
    },
    watch: {
        editId: {
            handler() {
                if (this.editId) this.getDetail()
            },
            immediate: true,
            deep: true
        },
    },
    onLoad() { },
    mounted() {
        this.getRegionList();
    },
    methods: {
        pickerChange(type, e) {
            // console.log(type, e.detail.value);
            if (type == 'sex') {
                this.form.sex_index = e.detail.value;
                this.form.sex = this.options.sex[e.detail.value];
            }
            if (type == 'region') {
                this.room_keys[0] = {
                    name: this.options.region[e.detail.value].areaName,
                    key: e.detail.value,
                    id: this.options.region[e.detail.value].areaId,
                };
                this.getRoomList(this.options.region[e.detail.value].areaId);
            }
            if (type == 'room') {
                // this.room_keys = {
                //     name: this.options.room[e.detail.value].areaName,
                //     key: e.detail.value,
                //     id: this.options.room[e.detail.value].areaId,
                // };
                let find = this.room_lists.find(li => {
                    return li.id == this.options.room[e.detail.value].roomId
                })
                if (find) {
                    this.$comFun.toast('当前房间已被选择');
                    return;
                }
                this.room_lists.push({
                    name: this.options.room[e.detail.value].roomName,
                    areaName: this.room_keys[0].name,
                    id: this.options.room[e.detail.value].roomId,
                })
                this.room_keys[0] = { name: '', key: '', id: '' };
            }
        },
        deleteRooms(key) {
            this.room_lists.splice(key, 1);
        },
        async getRegionList() {
            let data = {
                pageNum: 1,
                pageSize: 10000,
                statRoom: 0
            };
            const res = await this.$request.get('mobile/manager/area', data);
            this.$comFun.closeLoading();
            // console.log(res);
            if (res.code == 200) {
                this.options.region = res.data.data;
            }
        },
        async getRoomList(areaId) {
            let data = {
                pageNum: 1,
                pageSize: 10000,
                areaId: areaId
            };
            const res = await this.$request.get(`mobile/manager/area/${areaId}/room`, data);
            this.$comFun.closeLoading();
            // console.log(res);
            if (res.code == 200) {
                this.options.room = res.data.data;
            }
        },
        async getDetail() {
            const that = this;
            that.$comFun.openLoading();
            const res = await that.$request.get(`/mobile/manager/tenant/${that.editId}`, {});
            // console.log(res);
            that.$comFun.closeLoading();
            if (res.code == 200) {
                this.room_lists = res.data.rooms ? res.data.rooms : [];
                this.userStatus = Number(res.data.status);
                console.log(this.userStatus);

                this.form = {
                    username: res.data.username,
                    sex: res.data.sex,
                    sex_index: res.data.sex == '男' ? 0 : 1,
                    phone: res.data.phone,
                    backup_phone: res.data.backupPhone,
                    room_ids: res.data.rooms ? res.data.rooms.map(li => {
                        return li.id
                    }) : []
                }
            }
        },
        async toSubmit() {
            const that = this;
            const form = JSON.parse(JSON.stringify(that.form));
            if (!form.username) {
                that.$comFun.toast('请填写客户名称');
                return;
            }
            if (!form.sex) {
                that.$comFun.toast('请选择性别');
                return;
            }
            if (!that.$comFun.ValidateMobile(form.phone)) {
                that.$comFun.toast('请填写正确的手机号');
                return;
            }
            if (!that.$comFun.ValidateMobile(form.backup_phone)) {
                that.$comFun.toast('请填写正确的备用手机号');
                return;
            }
            if (that.room_lists.length == 0) {
                that.$comFun.toast('请绑定房间');
                return;
            }
            uni.showModal({
                title: '提示',
                content: '是否确定保存？',
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading();
                        let res;
                        form.room_ids = that.room_lists.map(li => {
                            return li.id
                        })
                        delete form.sex_index;
                        form.sex = form.sex == '男' ? 1 : 2;// 1：男，2：女
                        console.log(form);
                        if (that.editId) {
                            res = await that.$request.put(`mobile/manager/tenant/${that.editId}`, {
                                ...form,
                            });
                        } else {
                            res = await that.$request.post('mobile/manager/tenant', form);
                        }
                        // console.log(res);
                        that.$comFun.closeLoading();
                        if (res.code == 200) {
                            that.$comFun.toast('保存成功');
                            uni.$emit(`manageListReload_3`);
                            setTimeout(() => {
                                that.$comFun.closeWin();
                            }, 1000)
                        } else {
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        },
        toDelete() {
            const that = this;
            uni.showModal({
                title: '提示',
                content: '是否确定删除？',
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading();
                        const res = await that.$request.delete(`/mobile/manager/tenant/${that.editId}`);
                        // console.log(res);
                        that.$comFun.closeLoading();
                        if (res.code == 200) {
                            that.$comFun.toast('删除成功');
                            uni.$emit(`manageListReload_3`);
                            setTimeout(() => {
                                that.$comFun.closeWin();
                            }, 1000)
                        } else {
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        },
        changeStatus() {
            const that = this;
            uni.showModal({
                title: '提示',
                content: `是否确定${this.userStatus == 1 ? '禁用' : '启用'}？`,
                success: async function (modalRes) {
                    if (modalRes.confirm) {
                        that.$comFun.openLoading();
                        const res = await that.$request.put(`/mobile/manager/tenant/status/${that.editId}`, {
                            status: that.userStatus == 1 ? 2 : 1
                        });
                        // console.log(res);
                        that.$comFun.closeLoading();
                        if (res.code == 200) {
                            that.$comFun.toast(`操作成功`);
                            that.userStatus = that.userStatus == 1 ? 2 : 1
                            uni.$emit(`manageListReload_3`);
                        } else {
                            that.$comFun.toast(res.msg);
                        }
                    }
                }
            });
        }
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/manage.scss";
</style>
